//
//  ViewController.m
//  DouyuAuthHost
//
//  Created by admin on 16/11/3.
//  Copyright © 2016年 douyu. All rights reserved.
//

#import "ViewController.h"
#import <Security/Security.h>

@implementation ViewController
{
    __weak IBOutlet NSTextField *_authKeyTextField;
    
}

- (void)setRepresentedObject:(id)representedObject {
    [super setRepresentedObject:representedObject];
    
    // Update the view, if already loaded.
}

- (void)viewDidLoad {
    [super viewDidLoad];
    /*
    NSString *authKey = [self readAuthKey];
    if (authKey.length > 0) {
        _authKeyTextField.stringValue = authKey;
    }
     */
}

- (IBAction)onSaveButtonClick:(NSButton *)sender {
    NSString *authKey = _authKeyTextField.stringValue;
    if (authKey.length > 0) {
        [self deleteAuthKey];
        [self storeAuthKey:authKey];
    }
    _authKeyTextField.stringValue = @"";
}

#pragma mark - keychain

- (NSString *)readAuthKey
{
    NSString *service = @"com.douyu.DouyuAuthHost";
    
    NSDictionary *query = @{
                            (id)kSecClass:(id)kSecClassGenericPassword,
                            (id)kSecAttrService:service,
                            (id)kSecAttrAccount:service,
                            (id)kSecReturnData:(id)kCFBooleanTrue
                            };
    CFDataRef data = NULL;
    OSStatus status = SecItemCopyMatching((CFDictionaryRef)query, (CFTypeRef *)&data);
    if (status != noErr) {
        NSLog(@"没有读取到密钥");
        return nil;
    }
    
    NSString *authKey = [[NSString alloc] initWithData:(__bridge NSData *)data encoding:NSUTF8StringEncoding];
    
    if (data) {
        CFRelease(data);
    }
    return authKey;
}

- (BOOL)storeAuthKey:(NSString *)authKey
{
    NSString *service = @"com.douyu.DouyuAuthHost";
    
    NSData *data = [authKey dataUsingEncoding:NSUTF8StringEncoding];
    
    NSDictionary *query = @{
                            (id)kSecClass:(id)kSecClassGenericPassword,
                            (id)kSecAttrService:service,
                            (id)kSecAttrAccount:service,
                            (id)kSecValueData:data
                            };
    OSStatus status = SecItemAdd((CFDictionaryRef)query, NULL);
    if (status != noErr) {
        NSLog(@"存储密钥失败");
        return NO;
    }
    return YES;
}

- (BOOL)deleteAuthKey
{
    NSString *service = @"com.douyu.DouyuAuthHost";
    
    NSDictionary *query = @{
                            (id)kSecClass:(id)kSecClassGenericPassword,
                            (id)kSecAttrService:service,
                            (id)kSecAttrAccount:service,
                            };
    OSStatus status = SecItemDelete((CFDictionaryRef)query);
    if (status != noErr) {
        NSLog(@"删除密钥失败");
        return NO;
    }
    return YES;
}

@end
